package com.sx.gongzhong.receiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;

import com.sx.gongzhong.R;
import com.sx.gongzhong.net.ServiceFactory;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.FileUtils;
import com.sx.gongzhong.utils.Global;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdateService extends Service {
    // 文件存储
    private File updateDir = null;
    private File updateFile = null;

    private static final int DOWNLOADING = 1; // 表示正在下载
    private static final int DOWNLOADED = 2; // 下载完毕
    private static final int DOWNLOAD_FAILED = 3; // 下载失败
    private boolean cancelFlag = false; // 取消下载标志位
    private int count = 0;
    private long length = 0;
    private int progress;
    private Intent intentService;

    // 在onStartCommand()方法中准备相关的下载工作：
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        this.intentService=intent;
        String path=intent.getStringExtra("APK_PATH");
        // 创建文件
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            updateDir = new File(FileUtils.getRootDirectory(),
                    Global.saveFileName);
            updateFile = new File(updateDir.getPath(), Global.apkName);
        }
            // 下载apk
            downloadAPK(path);
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    /**
     * 下载apk的线程
     */
    public void downloadAPK(final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                    updateDir = new File(Environment.getExternalStorageDirectory(), Global.saveFileName);
                    updateFile = new File(updateDir.getPath(), Global.apkName);
                    if (updateFile.exists() || updateDir.exists()) {
                        updateDir.delete();
                        updateFile.delete();
                    }
                } else {
                    stopService(intentService);
                    return;
                }
                FileOutputStream fos = null;
                InputStream is = null;
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setUseCaches(false);
                    length = conn.getContentLength();
                    is = conn.getInputStream();
                    if (!updateDir.exists()) {
                        updateDir.mkdirs();
                    }
                    if (!updateFile.exists()) {
                        updateFile.createNewFile();
                    }
                    fos = new FileOutputStream(updateFile,
                            true);
                    byte buf[] = new byte[1024*50];
                    do {
                        int numread = is.read(buf);
                        count += numread;
                       // progress = (int)((1.0f*count / length) * 100);
                        // 更新进度
                        handler.sendEmptyMessage(DOWNLOADING);
                        if (numread <= 0) {
                            // 下载完成通知安装
                            handler.sendEmptyMessage(DOWNLOADED);
                            cancelFlag = true;
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (!cancelFlag); // 点击取消就停止下载.
                } catch (Exception e) {
                    handler.sendEmptyMessage(DOWNLOAD_FAILED);
                    e.printStackTrace();
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            //  Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException e) {
                            // Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOADING:
                    showProgress();
                 //   mProgress.setProgress(progress);
                    break;
                case DOWNLOADED:
                    NotificationManager manager2=(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
                    builder.setTicker("下载完成")
                            .setContentTitle("下载完成")
                            .setContentInfo("已下载");
                    Notification n3 = builder.build();
                    manager2.notify(1003, n3);
                    manager2.cancel(1003);
                    stopService(intentService);

                    Intent intent = BaseUtil.getInstallIntent(updateFile);
                    getApplicationContext().startActivity(intent);
                    break;
                case DOWNLOAD_FAILED:
                    stopService(intentService);
                    break;
                default:
                    break;
            }
        }
    };

    private NotificationCompat.Builder builder=null;
    /**
     * 显示下载进度
     */
    private void showProgress() {
        if(builder==null){
            NotificationManager manager=(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
            builder=new NotificationCompat.Builder(getApplicationContext());
            builder.setSmallIcon(R.mipmap.logo)
                    .setProgress(100, 0, false)
                    .setTicker("开始下载")
                    .setContentTitle("正在下载...")
                    .setContentInfo("0/"+getFloat(length)+"M");
            Notification n=builder.build();
            manager.notify(1003, n);
        }else {
            NotificationManager manager1=(NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
            builder.setProgress(100,progress, false)
                    .setContentInfo(getFloat(count)+"/"+getFloat(length)+"M");
            Notification n2 = builder.build();
            manager1.notify(1003, n2);
        }
    }


    private float getFloat(long nub){
        return 1.0f*((int)(1.0f*nub/1024/1024*100))/100;
    }

}
